// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

// Copyright (C) 2012 stfour
// Copyright (C) 2012 JoostinOnline

/*
priiloader.c
Detects Priiloader's Autoboot and Return To settings
from loader.ini

By stfour
*/
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <ogc/machine/processor.h>
#include <ogc/ipc.h>
#include <ogc/isfs.h>
#include "debug.h"

void *allocate_memory(u32 size)
{
	void *temp;
	temp = memalign(32, (size+31)&(~31) );
	memset(temp, 0, (size+31)&(~31) );
	return temp;
}

typedef struct {
	u32 autoboot;
	u32 version;
	u32 ReturnTo;
} Settings;

enum {
	AUTOBOOT_DISABLED,
	AUTOBOOT_HBC,
	AUTOBOOT_BOOTMII_IOS,
	AUTOBOOT_SYS,
	AUTOBOOT_FILE,
	AUTOBOOT_ERROR
};
enum {
	RETURNTO_SYSMENU,
	RETURNTO_PRIILOADER,
	RETURNTO_AUTOBOOT
};


/*Returns true if both Return To and Autoboot are set to System Menu,
or if Priiloader is not installed.  Otherwise returns false.*/
bool GetIni (void) {
	u8 * loaderIniBuff = NULL;
	size_t loaderIniSize = 0;

	char path[ISFS_MAXPATH] ATTRIBUTE_ALIGN(32);

	Debug ("GetIni starting");

	// Read the loader.ini configuration file
	sprintf (path, "/title/00000001/00000002/data/loader.ini");

	// Get priiloader loader.ini files contents
	s32 fd = ISFS_Open (path, ISFS_OPEN_READ);

	Debug ("ISFS Open Passed");

	if (fd < 0)
	{
		// Priiloader probably isn't installed
		Debug ("fd is < 0, Priiloader probably isn't installed");
		return true;
	}
	Debug ("Priiloader is installed");

	loaderIniSize = ISFS_Seek(fd, 0, 2);
	if (loaderIniSize <= 0) return false;

	Debug("ISFS Seek Passed");

	if (loaderIniSize)
	{
		loaderIniBuff = allocate_memory(loaderIniSize);

		Debug("allocate_memory Passed");

		if (!loaderIniBuff)
		{
			ISFS_Close (fd);
			return false;
		}
		ISFS_Seek(fd, 0, 0);
		Debug("ISFS Seek2 Passed");

		ISFS_Read(fd, loaderIniBuff, loaderIniSize);
	}

	Debug("ISFS Read Passed");

	ISFS_Close (fd);

	Debug("ISFS Close Passed");

	Settings *settings=(Settings *)loaderIniBuff;

	return ((settings->autoboot == AUTOBOOT_SYS) && (settings->ReturnTo == RETURNTO_SYSMENU));
};// GetIni